package tptecnicas.logging;

import java.util.ArrayList;
import java.util.List;
import tptecnicas.printers.Writer;

/**
 * Clase encargada del control de todos los destinos configurados 
 * para loguear. Delega el mensaje reportado a todos los escritores
 * disponibles.
 */
public class LogOuputManager {

	private List<Writer> writerslist;

	public LogOuputManager() {
		this.writerslist = new ArrayList<>();
	}
	
	public void addWriter(Writer writer)	{
		if(!this.isWriterUpdated(writer)) {
			addParticularWriter(writer);
		}
	}
	
	private boolean isWriterUpdated(Writer writer) {
		if(this.writerslist.contains(writer)) { // writers should redefine equals() method
			int position = this.writerslist.indexOf(writer);
			this.writerslist.set(position, writer);
			return true;
		}
		return false;
	}
	
	private void addParticularWriter(Writer writer) {
		this.writerslist.add(writer);
	}
	
	public void write(MessageInfo message) {
		for (Writer writer : this.writerslist) {
			writer.write(message);
		}		
	}

	public void pause(Writer writer) {
		Writer myWriter = this.getWriter(writer);
		if (myWriter != null) {
			myWriter.pause();
		}
	}

	public void unPause(Writer writer) {
		Writer myWriter = this.getWriter(writer);
		if (myWriter != null) {
			myWriter.unpause();
		}
	}
	
	private Writer getWriter(Writer writer) {
		for (Writer myWriter : this.writerslist) {
			if (myWriter.equals(writer)) {
				return myWriter;
			}
		}
		return null;
	}
	
	public int count() {
		return this.writerslist.size();
	}

	public List<Writer> getWriters() {
		return this.writerslist;
	}

	public boolean isLevelEnabled(String level) {
		for (Writer myWriter : this.writerslist) {
			if (myWriter.hasLevelEnabled(level)) {
				return true;
			}
		}
		return false;
	}
}
